﻿var consentWindow;

$(function() {
    InitializeCS();

    prm.add_endRequest(function(sender, args) {
        InitializeCS();
    }
    );


});

function InitializeCS() {
    $('.csresult input:checkbox').change(function() {
        $(this).parents("tr").toggleClass("selected");
    });

    $('.livebutton').change(function() {
        OpenJqueryDialog();
        DisableEverything(true);

    });

    $('.googlebutton input:radio, .manualbutton input:radio').change(function() {
        DisableEverything(false);
        //abortTask();
    });

    $('#csmbutton').click(function() {
        AddMoreContacts();
    });

    $('.delauthbutton').click(function() {
        OpenLiveConsentWindow();
        CheckConsendToken();
    });
    
    try
    {
        $('.cssearchbox').quicksearch('table.csselectresult tbody tr');
    }catch(ex){}
}

function abortTask() {
    var obj = Sys.WebForms.PageRequestManager.getInstance();
    if (obj.get_isInAsyncPostBack())
        obj.abortPostBack();
}

function DisableEverything(bool) {

    $('.initialcspanel input:text, .initialcspanel input:password, .csbutton').attr('disabled', bool);
    if (!bool) {
        clearTimeout(checkTimer);
    }
}

function OpenLiveConsentWindow() {
    consentWindow = window.open(consentUrl, 'delauthwindow', 'menubar=no,toolbar=no,status=yes,modal=yes');
}

var checkTimer;
function CheckConsendToken() {
    if ($.cookie("lid") != null) {
        CloseJqueryDialog();
        clearTimeout(checkTimer);
        eval($('.csbutton').attr("href"));
    }
    else {
        checkTimer = setTimeout(CheckConsendToken, 500);
    }
}

function AddMoreContacts() {
    var name = $.trim($('#mname').val());
    var mail = $.trim($('#memail').val()).toLowerCase();
    if (mail != "") {
        var shouldAppend = true;
        
        var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
        if (!filter.test(mail)) {
            shouldAppend = false;
        }
        else {

            $('.cssendlist td.mailaddr').each(function() {
                if ($.trim($(this).text()).toLowerCase() == mail)
                    shouldAppend = false;
                return false;
            });
        }

        if (shouldAppend) {
            var tb = $('.cssendlist tbody');
            var row = '<tr><td>' + name + '</td><td class="mailaddr">' + mail + '</td><td></td></tr>';
            tb.append(row);
            var list = $('.extrainput input:hidden').val();
            $('.extrainput input:hidden').val(list + "|" + name + "," + mail);
            $('#selectCount').text($('.cssendlist tr').length-1);
            $('#mname').val("");
            $('#memail').val("");
            $('#mname').focus();
        }
    }
}